import { Injectable, Inject, OnModuleDestroy } from '@nestjs/common';
import { RedisClientType } from 'redis';

@Injectable()
export class RedisService implements OnModuleDestroy {
  constructor(
    @Inject('REDIS_CLIENT')
    private readonly redisClient: RedisClientType,
  ) {}

  async onModuleDestroy() {
    await this.redisClient.quit();
  }

  // 基础操作
  async get(key: string): Promise<string | null> {
    return await this.redisClient.get(key);
  }

  async set(key: string, value: string, ttl?: number): Promise<void> {
    if (ttl) {
      await this.redisClient.setEx(key, ttl, value);
    } else {
      await this.redisClient.set(key, value);
    }
  }

  async del(key: string): Promise<number> {
    return await this.redisClient.del(key);
  }

  async exists(key: string): Promise<number> {
    return await this.redisClient.exists(key);
  }

  async expire(key: string, seconds: number): Promise<boolean> {
    return await this.redisClient.expire(key, seconds);
  }

  async ttl(key: string): Promise<number> {
    return await this.redisClient.ttl(key);
  }

  // Hash操作
  async hGet(key: string, field: string): Promise<string | undefined> {
    return await this.redisClient.hGet(key, field);
  }

  async hSet(key: string, field: string, value: string): Promise<number> {
    return await this.redisClient.hSet(key, field, value);
  }

  async hGetAll(key: string): Promise<Record<string, string>> {
    return await this.redisClient.hGetAll(key);
  }

  async hDel(key: string, field: string): Promise<number> {
    return await this.redisClient.hDel(key, field);
  }

  async hExists(key: string, field: string): Promise<boolean> {
    return await this.redisClient.hExists(key, field);
  }

  // Set操作
  async sAdd(key: string, member: string): Promise<number> {
    return await this.redisClient.sAdd(key, member);
  }

  async sRem(key: string, member: string): Promise<number> {
    return await this.redisClient.sRem(key, member);
  }

  async sMembers(key: string): Promise<string[]> {
    return await this.redisClient.sMembers(key);
  }

  async sIsMember(key: string, member: string): Promise<boolean> {
    return await this.redisClient.sIsMember(key, member);
  }

  async sCard(key: string): Promise<number> {
    return await this.redisClient.sCard(key);
  }

  // List操作
  async lPush(key: string, element: string): Promise<number> {
    return await this.redisClient.lPush(key, element);
  }

  async rPush(key: string, element: string): Promise<number> {
    return await this.redisClient.rPush(key, element);
  }

  async lPop(key: string): Promise<string | null> {
    return await this.redisClient.lPop(key);
  }

  async rPop(key: string): Promise<string | null> {
    return await this.redisClient.rPop(key);
  }

  async lRange(key: string, start: number, stop: number): Promise<string[]> {
    return await this.redisClient.lRange(key, start, stop);
  }

  async lLen(key: string): Promise<number> {
    return await this.redisClient.lLen(key);
  }

  // 模式匹配
  async keys(pattern: string): Promise<string[]> {
    return await this.redisClient.keys(pattern);
  }

  // JSON操作（如果需要）
  async setJson(key: string, value: any, ttl?: number): Promise<void> {
    const jsonString = JSON.stringify(value);
    await this.set(key, jsonString, ttl);
  }

  async getJson<T>(key: string): Promise<T | null> {
    const jsonString = await this.get(key);
    if (!jsonString) return null;
    try {
      return JSON.parse(jsonString) as T;
    } catch (error) {
      console.error('JSON解析错误:', error);
      return null;
    }
  }

  // 房间相关操作
  async setRoomData(
    roomId: string,
    data: any,
    ttl: number = 300,
  ): Promise<void> {
    const key = `room:${roomId}`;
    await this.setJson(key, data, ttl);
  }

  async getRoomData(roomId: string): Promise<any> {
    const key = `room:${roomId}`;
    return await this.getJson(key);
  }

  async deleteRoom(roomId: string): Promise<number> {
    const key = `room:${roomId}`;
    return await this.del(key);
  }

  async addParticipantToRoom(
    roomId: string,
    participantId: string,
  ): Promise<number> {
    const key = `room:${roomId}:participants`;
    return await this.sAdd(key, participantId);
  }

  async removeParticipantFromRoom(
    roomId: string,
    participantId: string,
  ): Promise<number> {
    const key = `room:${roomId}:participants`;
    return await this.sRem(key, participantId);
  }

  async getRoomParticipants(roomId: string): Promise<string[]> {
    const key = `room:${roomId}:participants`;
    return await this.sMembers(key);
  }

  async getRoomParticipantCount(roomId: string): Promise<number> {
    const key = `room:${roomId}:participants`;
    return await this.sCard(key);
  }

  // 用户会话管理
  async setUserSession(
    userId: string,
    sessionData: any,
    ttl: number = 3600,
  ): Promise<void> {
    const key = `session:${userId}`;
    await this.setJson(key, sessionData, ttl);
  }

  async getUserSession(userId: string): Promise<any> {
    const key = `session:${userId}`;
    return await this.getJson(key);
  }

  async deleteUserSession(userId: string): Promise<number> {
    const key = `session:${userId}`;
    return await this.del(key);
  }

  // 统计信息
  async incrementCounter(key: string, ttl?: number): Promise<number> {
    const result = await this.redisClient.incr(key);
    if (ttl && result === 1) {
      await this.expire(key, ttl);
    }
    return result;
  }

  async getCounter(key: string): Promise<number> {
    const value = await this.get(key);
    return value ? parseInt(value, 10) : 0;
  }
}
